import Command from '@ckeditor/ckeditor5-core/src/command';
import first from '@ckeditor/ckeditor5-utils/src/first';

const FONT_COLOR = 'fontColor';

export default class FontColorCommand extends Command {
	/**
	 * @inheritDoc
	 */
	refresh() {
		const model = this.editor.model;
		const doc = model.document;

		/**
		 * A value indicating whether the command is active. If the selection has some highlight attribute,
		 * it corresponds to the value of that attribute.
		 *
		 * @observable
		 * @readonly
		 * @member {undefined|String} module:highlight/highlightcommand~HighlightCommand#value
		 */
		this.value = doc.selection.getAttribute( 'fontColor' );
		this.isEnabled = model.schema.checkAttributeInSelection( doc.selection, 'fontColor' );
	}

	/**
	 * Executes the command.
	 *
	 * @protected
	 * @param {Object} [options] Options for the executed command.
	 * @param {String} [options.value] The value to apply.
	 *
	 * @fires execute
	 */
	execute( options = {} ) {
		const model = this.editor.model;
		const document = model.document;
		const selection = document.selection;

		const fontColorValue = options.value;

		model.change( writer => {
			const ranges = model.schema.getValidRanges( selection.getRanges(), 'fontColor' );

			if ( selection.isCollapsed ) {
					writer.setSelectionAttribute( 'fontColor', fontColorValue );
			} else {
				for ( const range of ranges ) {
					if ( fontColorValue ) {
						writer.setAttribute( 'fontColor', fontColorValue, range );
					} else {
						writer.removeAttribute( 'fontColor', range );
					}
				}
			}
		} );
	}
}
